﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using XbdSoft.WPFVersion.Effect;
using System.Windows.Interop;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Unity;
using XbdSoft.WPFVersion.Common;
using XbdSoft.Contract;
using XbdSoft.Client;
using XbdSoft.Domain;
using XbdSoft.WPFVersion.View;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using XbdSoft.WPFVersion.UserControls;
using mshtml;
using System.Net;
using System.IO;

namespace XbdSoft.WPFVersion
{
    /// <summary>
    /// Interaction logic for Shell.xaml
    /// </summary>
    public partial class Shell :Window
    {  

        #region Set Window Long. Only run .NET 3.5. The reason hasn't been found
        const int GWL_EXSTYLE = (-20);
        const int GWL_STYLE = -16;
        const UInt32 WS_POPUP = 0x80000000;
        const UInt32 WS_CLIPCHILDREN = 0x02000000;
        [DllImport("user32.dll")]
        static extern int SetWindowLong(IntPtr hWnd, int nIndex, UInt32 dwNewLong);

        private void SetWindowLong(IntPtr hWnd)
        {
            Background = new SolidColorBrush(Colors.LightGray);
            //WindowStyle = System.Windows.WindowStyle.None;
            SetWindowLong(hWnd, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN); 
        }

        protected override void OnInitialized(EventArgs e)
        { 
            base.OnInitialized(e);
        }
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            //WindowStyle = System.Windows.WindowStyle.None;
            //AllowsTransparency = true;
            Background = new SolidColorBrush(Colors.Transparent);
            IntPtr hWnd = new WindowInteropHelper(this).Handle;
            SetWindowLong(hWnd);
        }
        #endregion

        #region Set Message Proc Hook
        protected void SetMessageProcHook(IntPtr hWnd)
        {
            HwndSource.FromHwnd(hWnd).AddHook(WndProc);
        }

        protected const int USER = 0x400;
        protected const int DOWNLOADMSG = USER + 1;
        protected IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case DOWNLOADMSG:
                    {
                        //wParam =100
                        try
                        {
                            var id = (UInt32)lParam;
                            var resource = default(AudioResource);
                            using (var downloadService = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                            {
                                resource = downloadService.Object.GetAudioResource(id);
                            }
                            if (resource != null)
                            {
                                DownloadTabItem.IsSelected = true;
                                downloadView.Download(resource);
                            }
                        }
                        catch(Exception ex) 
                        { 
                        }
                        break;
                    }
            }

            return IntPtr.Zero;
        }

        #endregion

        #region Fields
        private const string XbdWebsiteUrl = "http://www.xbd61.com";
        private WindowState lastWindowState; 
        protected readonly IEventAggregator EventAggregator = null;
        protected readonly IUnityContainer Container = null;
        protected IntPtr Handle = IntPtr.Zero;
        private ConfigurationWindow configurationWindow = null;
        #endregion

        #region Ctor
        public Shell(IEventAggregator eventAggregator, IUnityContainer container)
        { 
            EventAggregator = eventAggregator;
            Container = container;
            InitializeComponent();
            EventAggregator.GetEvent<DownloadResourceEvent>().Subscribe(DownloadResourceAction);
            notifyIcon.ContextMenu.Visibility = System.Windows.Visibility.Collapsed;
            EventAggregator.GetEvent<TryListenEvent>().Subscribe(TryListenEvent_Published);
        }
        #endregion

        #region Download Resource Event
        public void DownloadResourceAction(DownloadResourceEventArgs e)
        {
            DownloadTabItem.IsSelected = true;
            RecommendDownloadTabItem.IsSelected = false;
            if (e.Resource != null)
            {
                Download(e.Resource);
            }
        }

        public void Download(int resourceID)
        {
            try
            {
                var resource =default(AudioResource);
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    resource = service.Object.GetAudioResource(resourceID);
                }
                if (resource != null)
                {
                    Download(resource);
                }
            }
            catch { }
        }

        public void Download(AudioResource resource)
        {
            if (resource != null)
            {
                DownloadTabItem.IsSelected = true;
                RecommendDownloadTabItem.IsSelected = false;
                downloadView.Download(resource);
            } 
        }
        #endregion

        #region Loaded

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IntPtr hWnd = new System.Windows.Interop.WindowInteropHelper(this).Handle; 
            SetMessageProcHook(hWnd);
            InfoWebBrowser.Navigate(new Uri(GetNavigationUrl(), UriKind.Absolute));
            InfoWebBrowser.CaptureMouse();
            Thread.Sleep(200);
            InfoWebBrowser.ReleaseMouseCapture();
            this.WelComeTextBlock.Text = string.Format("您好，{0}",Util.UserName??String.Empty);

            InitAdvertise();
        }

        #endregion         

        #region Mouse Move on the Header of window
        public void DragWindow(object sender, MouseButtonEventArgs args)
        {
            this.DragMove();
        }

        #endregion

        #region Close
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
            Process.GetCurrentProcess().Kill();
        }
        #endregion

        #region Notify Icon Events
        private void OnNotifyIconDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
				ShowWindow();
            }
        }

        private void OnOpenClick(object sender, RoutedEventArgs e)
        { 
             ShowWindow(); 
        }

        private void OnHideClick(object sender, RoutedEventArgs e)
        {
			HideWindow();
        }

        private void OnExitClick(object sender, RoutedEventArgs e)
        {
            this.Close();
            Process.GetCurrentProcess().Kill();
        }

        private void OnConfigurationClick(object sender, RoutedEventArgs e)
        {
            try
            {
               
                //configurationWindow = new ConfigurationWindow();
                //configurationWindow.ShowDialog();
                if (configurationWindow == null)
                {
                    configurationWindow = new ConfigurationWindow();
                    configurationWindow.Topmost = true;
                    configurationWindow.ShowDialog();
                }
                else
                {
                    configurationWindow.Close();
                    configurationWindow = null;
                    ShowWindow(false);
                    configurationWindow = new ConfigurationWindow();
                    configurationWindow.Topmost = true;
                    configurationWindow.ShowDialog();
                } 
            }
            catch { }
            //else
            //{
            //    //configurationWindow.ShowDialog();
            //    configurationWindow.Show();
            //    configurationWindow.Visibility = System.Windows.Visibility.Visible;
            //    //configurationWindow.Topmost = true;
            //}
        }

        private void MinButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
			HideWindow();
        }
 
		private void ShowWindow(bool topMost=true)
        { 
            if (HasLogin)
            {
                this.Show();
                Visibility = System.Windows.Visibility.Visible;
                Topmost = topMost;
                InfoWebBrowser.UpdateLayout();
                this.WindowState = this.lastWindowState;
            }
		}
		private void HideWindow()
		{
            if (HasLogin)
            {
                this.lastWindowState = this.WindowState;
                this.Hide();
            }
		}
 
        #endregion

        #region Tab Control Selection Changed
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (MainTabControl.SelectedItem == InfoTabItem)
            {
                if (InfoWebBrowser.Document == null)
                {
                    InfoWebBrowser.Navigate(new Uri(GetNavigationUrl()));
                }
                else
                {
                    var htmlDocument = InfoWebBrowser.Document as HTMLDocument;
                    htmlDocument.focus();
                }
                recommendDownloadView.PauseTryListen();
                searchResouceView.PauseTryListen();
                ShowTryListenMenuItem.Visibility = System.Windows.Visibility.Hidden;
                winMediaPlayerHost.Visibility = System.Windows.Visibility.Hidden;
            }
            else if (MainTabControl.SelectedItem == SearchTabItem)
            {
                searchResouceView.CanShow = true;
                recommendDownloadView.PauseTryListen();
                ShowTryListenMenuItem.Visibility = System.Windows.Visibility.Visible;
            }
            else if (MainTabControl.SelectedItem == RecommendDownloadTabItem)
            {
                recommendDownloadView.CanShow = true;
                searchResouceView.PauseTryListen();
                recommendDownloadView.ReloadTryListen();
                ShowTryListenMenuItem.Visibility = System.Windows.Visibility.Visible;
            }
        }

        #endregion

        #region Properties
        private bool hasLogin = false;
        public bool HasLogin
        {
            get { return hasLogin; }
            set
            {
                hasLogin = value;
                notifyIcon.ContextMenu.Visibility = System.Windows.Visibility.Visible;
            }
        }
        #endregion

        #region Navigation Url

        protected string GetNavigationUrl()
        {
            var url = "http://www.xbd61.com";
            try
            {
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    var usepass = service.Object.GetUsePassword()??"123";
                    var requestUrl = string.Format("http://www.xbd61.com/api/api_savelogin.asp?username={0}&password={1}&usepass={2}", Util.UserName, Util.Password, usepass);
                    return requestUrl;
                }
            }
            catch { }
            return url;
        }
        #endregion

        #region Menu Item Events

        private const string SearchTabItemName = "searchTabItem";
        private void SearchMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var searchTabItemControl = default(TabItem);
            foreach (var tabItem in MainTabControl.Items)
            {
                var tabItemControl = tabItem as TabItem;
                if (tabItemControl.Name == SearchTabItemName)
                {
                    searchTabItemControl = tabItemControl;
                    break;
                }
            }
            if (searchTabItemControl == null)
            {
                searchTabItemControl = new TabItem();
                searchTabItemControl.Name = SearchTabItemName;
                searchTabItemControl.Header = "搜索MP3";
                searchTabItemControl.Content = new SearchResourceView();
                MainTabControl.Items.Add(searchTabItemControl);
            }
            MainTabControl.SelectedItem = searchTabItemControl;
        }

        private void SetupMenuItem_Click(object sender, RoutedEventArgs e)
        {
            configurationWindow = Container.Resolve<ConfigurationWindow>();
            configurationWindow.ShowDialog(); 
        }

        private void AdviticeTextBlock_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            string url = AdvertisementMimi.SiteUrl ?? XbdWebsiteUrl;
            Process.Start(url);         
        }

        #endregion
		
		#region

        private AdvertisementMimi AdvertisementMimi = null;
        private int currentIndex = 0;
        private List<AdvertisementMimi> allAdvertisementMimis = new List<AdvertisementMimi>();
        private void InitAdvertise()
        {
            using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
            {
                allAdvertisementMimis = service.Object.GetAllAdvertisementMimis();
            }
            if (allAdvertisementMimis == null || allAdvertisementMimis.Count <= 0)
            {
                allAdvertisementMimis.Add(new AdvertisementMimi() { 
                    SiteUrl =XbdWebsiteUrl,
                    SiteName ="小布叮优惠"
                });
                allAdvertisementMimis.Add(new AdvertisementMimi()
                {
                    SiteUrl = XbdWebsiteUrl,
                    SiteName = "小布叮优惠2"
                });
            }
            AdvertisementMimi = allAdvertisementMimis[currentIndex];
            AdvitiseTextBlock.Text = AdvertisementMimi.SiteName;
            BeginMove();
        }

		public double AdviticeLeft = 10F;
        public double AdviticeDuration = 20;
		private void BeginMove()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(10);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

            
		}

        void timer_Tick(object sender, EventArgs e)
        {
            Toggle();
            
        }

        void Toggle()
        {
            if (currentIndex < allAdvertisementMimis.Count - 1)
                currentIndex++;
            else
                currentIndex = 0;
            AdvertisementMimi = allAdvertisementMimis[currentIndex];
            AdvitiseTextBlock.Text = AdvertisementMimi.SiteName;

            Storyboard storyBoard = new Storyboard();
            DoubleAnimation advitiseTextblockLeftAnimation = new DoubleAnimation();
            advitiseTextblockLeftAnimation.From = 0;
            advitiseTextblockLeftAnimation.To = 100;
            advitiseTextblockLeftAnimation.Duration = new Duration(TimeSpan.FromSeconds(2));
            storyBoard.Children.Add(advitiseTextblockLeftAnimation);
            Storyboard.SetTarget(advitiseTextblockLeftAnimation, AdvitiseTextBlock);
            Storyboard.SetTargetProperty(advitiseTextblockLeftAnimation, new PropertyPath(TextBlock.OpacityProperty));

            //storyBoard.AutoReverse = true;
            storyBoard.Completed += new EventHandler(storyBoard_Completed);
            storyBoard.Begin();
        }
        void storyBoard_Completed(object sender, EventArgs e)
        {
             
        }
          
		#endregion

        private void AdvitiseTextBlock_Click(object sender, RoutedEventArgs e)
        {

        }

        private void InfoWebBrowser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            var htmlDocument = InfoWebBrowser.Document as HTMLDocument;
            htmlDocument.focus();
            htmlDocument.documentElement.style.overflow = "hidden";
            htmlDocument.body.setAttribute("scroll","no");
        }

        private void ShowTryListenMenuItem_Click(object sender, RoutedEventArgs e)
        {
            winMediaPlayerHost.Visibility = winMediaPlayerHost.Visibility == System.Windows.Visibility.Visible
                ? Visibility.Collapsed : Visibility.Visible;
            ShowTryListenMenuItem.Header = winMediaPlayerHost.Visibility == System.Windows.Visibility.Visible ? "隐藏试听" : "显示试听";
        }
        public void TryListenEvent_Published(TryListenEventArgs e)
        {
            var id = e.ResourceID;
            try
            {
                var url = string.Empty;
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    url = service.Object.GetDownloadUrl(id);
                }
                winMediaPlayer.Url = url;
                winMediaPlayer.Play();
                winMediaPlayerHost.Visibility = System.Windows.Visibility.Visible;
                ShowTryListenMenuItem.Header = "隐藏试听";
            }
            catch
            {
                winMediaPlayer.Close();
            }
        }
    }


    //[StructLayout(LayoutKind.Sequential)]
    //public struct SENDDATASTRUCT
    //{
    //    public UInt32 dwData;
    //    public UInt32 cbData; 
    //    public string lpData;
    //}
}
